package org.budo.phone.location.service.qihu;

import org.budo.phone.location.service.api.AbstractBudoPhoneLocation;
import org.budo.phone.location.service.api.BudoPhoneLocation;
import org.budo.phone.location.service.api.BudoPhoneLocationService;
import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;
import org.budo.support.lang.util.StringUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Slf4j
public class QihuPhoneLocationService implements BudoPhoneLocationService {
    private static final String API_URL = "http://cx.shouji.360.cn/phonearea.php";

    @Override
    public BudoPhoneLocation seekPhoneLocation(String phone) {
        try {
            return this.seek(phone);
        } catch (Throwable e) {
            log.error("#25 phone=" + phone + ", this=" + this + ", e=" + e, e);
            return null;
        }
    }

    private BudoPhoneLocation seek(String phone) {
        Request request = new Request();
        request.setUrl(API_URL);
        request.setParameter("number", phone);

        Response response = request.execute();
        String responseBody = response.getBody();
        if (response.getStatus() > 200 || StringUtil.isEmpty(responseBody)) {
            log.error("#38 request=" + request + ", response=" + response);
            return null;
        }

        // {"code":0,"data":{"province":"\u56db\u5ddd","city":"\u6210\u90fd","sp":"\u7535\u4fe1"}}
        JSONObject jsonObject = JSON.parseObject(responseBody);
        JSONObject data = jsonObject.getJSONObject("data");

        // {"code":1}
        if (null == data) {
            log.info("#50 return null, phone=" + phone + ", responseBody=" + responseBody);
            return null;
        }

        String province = data.getString("province");
        String city = data.getString("city");
        String serviceProvider = data.getString("sp");

        // 运营商可能返回空
        // {"code":0,"data":{"province":"\u4e0a\u6d77","city":"","sp":"\u79fb\u52a8"}}
        if (StringUtil.isEmpty(province) && StringUtil.isEmpty(city)) {
            log.info("#60 return null, phone=" + phone + ", responseBody=" + responseBody);
            return null;
        }

        return new AbstractBudoPhoneLocation(province, city, serviceProvider);
    }
}